
from questions.models import Label
from questions.serializers import LabelSerializerSimple, QuestionSerializerForList, ReplySerializerForList

from articles.serializers import ArticleListSerializer
from jobs.serializers import EnterpriseSerializerSimple
import re
from django_redis import get_redis_connection
from rest_framework import serializers
from users.models import User

class UserSerializer(serializers.ModelSerializer):
    #揣培洋 -- 8.1 用户序列化器
    labels = LabelSerializerSimple(required=False, many=True)
    username = serializers.CharField(read_only=True)
    questions = QuestionSerializerForList(read_only=True, many=True)
    answer_question = ReplySerializerForList(read_only=True, many=True)
    collected_articles =ArticleListSerializer(read_only=True, many=True)
    enterpises = EnterpriseSerializerSimple(read_only=True, many=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile','realname','birthday','sex','avatar',
                  'website','email','city', 'address','labels','questions','answer_question',
                  'collected_articles','enterpises')



class UserLabelSerializer(serializers.ModelSerializer):
    # 揣培洋 -- 8.2 个人信息序列化器
    labels = serializers.PrimaryKeyRelatedField(required=True,
                                                many=True,
                                                queryset=Label.objects.all())

    class Meta:
        model = User
        fields = ('id','labels')

class SetPwdSerializer(serializers.ModelSerializer):
    #揣培洋 -- 8.3 修改密码序列化器
    class Meta:
        model = User
        fields = ('password',)
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user








class AuthSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    token = serializers.CharField(label="token", read_only = True)

    class Meta:
        model = User
        fields = ("id", "username", "mobile", "sms_code", "avatar", "password", "token")
        extra_kwargs = {
            "password": {
                "write_only": True,
                "required": True
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[345789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    def validate(self, attrs):
        redis_conn = get_redis_connection('verify_code')
        mobile = attrs.get("mobile")
        sms = attrs.get('sms_code')
        sms_server = redis_conn.get("sms_%s" % mobile)
        if sms_server is None:

            raise serializers.ValidationError("验证码过期")
        if sms != sms_server.decode():
            raise serializers.ValidationError("验证码错误")
        return attrs


    def create(self, validated_data):
        del validated_data['sms_code']
        user = super().create(validated_data)
        user.set_password(validated_data["password"])

        user.save()
        from rest_framework_jwt.settings import api_settings

        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class UserLogSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label="短信验证码", write_only=True)
    token = serializers.CharField(label="token", read_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "mobile", "sms_code", "avatar", "password", "token")
        extra_kwargs = {
            "password": {
                "write_only": True,
                "required": True
            }
        }

        def validate_mobile(self, value):
            if not re.match(r'^1[345789]\d{9}$', value):
                raise serializers.ValidationError('手机号格式不正确')
            return value

        def validate(self, attrs):
            redis_conn = get_redis_connection('verify_code')
            mobile = attrs.get("mobile")
            sms = attrs.get('sms_code')
            sms_server = redis_conn("sms_%s" % mobile)
            if sms_server is None:
                raise serializers.ValidationError("验证码过期")

            if sms != sms_server.decode():
                raise serializers.ValidationError("验证码错误")

            return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        user = super().create(validated_data)
        user.set_password(validated_data["password"])

        user.save()
        from rest_framework_jwt.settings import api_settings

        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        user.token = token

        return user
